package com.ws.common;


import com.github.pagehelper.BasePageHelper;
import com.ws.util.PaasSqlUtil;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.util.Arrays;
import java.util.List;
import java.util.Properties;

/**
 * @author ：ws
 * @date ：Created in 2020/8/11 17:00
 * @description：TODO
 * @modified By：
 * @version: 1.0.0
 */
@Intercepts({@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class,
        RowBounds.class, ResultHandler.class})})
public class PaasPageHelper extends BasePageHelper implements Interceptor {
    private final PaasSqlUtil sqlUtil = new PaasSqlUtil();

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StackTraceElement[] stackTrace = (new Throwable()).getStackTrace();
        List<StackTraceElement> stackLst = Arrays.asList(stackTrace);
        long cnt = stackLst.stream().filter((e) -> {
            return e.getClassName().contains("PaasPageHelper");
        }).count();
        return cnt < 2L ? this.sqlUtil.intercept(invocation) : invocation.proceed();
    }
    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }
    @Override
    public void setProperties(Properties properties) {
        this.sqlUtil.setProperties(properties);
    }
}